<template>
  <div class="house-type-container">
    <el-table
      :data="tableData"
      class="custom-table"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="name"
        label="房屋类型分类"
        width="160"
        header-align="center"
        align="left">
      </el-table-column>
      <el-table-column
        prop="description"
        label="分类描述"
        width="220"
        header-align="center"
        align="left">
      </el-table-column>
      <el-table-column
        prop="displayOrder"
        label="排序"
        width="110"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        prop="roomPrice"
        label="房间价格"
        width="100"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        prop="remainingRooms"
        label="剩余间数"
        width="100"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        prop="landlordName"
        label="所属房东"
        width="120"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="联系电话"
        width="120"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
        header-align="center"
        align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        width="220"

        align="center"
        fixed="right">
        <template slot-scope="scope">
            <el-button
              title="编辑房屋类型"
              size="mini"
              @click="handleEdit(scope.$index, scope.row, '编辑房屋类型')">
              编辑
            </el-button>
            <el-button
              title="新增房屋类型"
              size="mini"
              @click="handleEdit(scope.$index, scope.row, '新增房屋类型')">
              新增
            </el-button>
            <el-button
              v-if="scope.row.parentId !== 0"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-dialog  :visible.sync="dialogVisible":close-on-click-modal="false" :title="title" >
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData"  size="medium" label-width="100px">
          <!--隐藏一个父分类的输入框，用于携带父分类的id-->
          <input type="hidden" :value="formData.parentId">
          <el-col :span="24">
            <el-form-item label="所属分类">
              <el-input v-model="formData.parentName" :maxlength="11" show-word-limit
                        :disabled='true' clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋类型" prop="itemTypeName">
              <el-input v-model="formData.name" placeholder="请输入房屋类型" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间价格" prop="roomPrice">
              <el-input-number v-model="formData.roomPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属房东" prop="landlordName">
              <el-input v-model="formData.landlordName" placeholder="请输入房屋类型" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余间数" prop="remainingRooms">
              <el-input-number v-model="formData.remainingRooms"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入房屋类型" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="displayOrder">
              <el-input-number v-model="formData.displayOrder"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="房屋描述" prop="description">
              <el-input v-model="formData.description" type="textarea" placeholder="请输入房屋描述"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { queryAllHouseTypes, handleDelete, addHouseType, editHouseType } from '@/api/md/House.js';
export default {
  name: 'Tree',
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      title: '新增房屋类型',
      loading: false,
      formData: {
        id: null,
        name: null,
        parentId: null,
        itemTypeName: null,
        roomPrice: null,
        remainingRooms: null,
        landlordName: null,
        phone: null,
        createTime: null,
        parentName: null,
        displayOrder: null,
        description: null,
      },
      }
    },
  methods: {
    queryAllHouseTypes() {
      this.loading = true;
      queryAllHouseTypes().then(response => {
        this.tableData = response.data;
        this.$message({
          message: '查询成功',
          type: 'success'
        })
        this.loading = false;
      }).catch(error => {
        this.$message.error('查询失败');
        this.loading = false;
      });
    },
    handleEdit(index, row, title) {
      this.title = title;
      this.dialogVisible = true;

      // 重置表单数据
      this.formData = JSON.parse(JSON.stringify(row)); // 深拷贝当前行数据

      if (title.includes('新增')) {
        // ============ 新增逻辑 ============
        this.formData = {
          parentId: row.id,       // 父ID设为当前行ID
          parentName: row.name,   // 父名称设为当前行名称
          // 重置其他字段为空
          name: '',
          roomPrice: null,
          remainingRooms: null,
          landlordName: '',
          phone: '',
          displayOrder: null,
          description: ''
        };
      } else {
        // ============ 编辑逻辑 ============
        // 设置父级名称（区分顶级分类和非顶级）
        if (row.parentId === 0) {
          this.formData.parentName = "房屋类型管理";
        } else {
          // 异步获取父级名称
          this.formData.parentName = "加载中..."; // 临时显示
          this.getParentName(row.parentId).then(name => {
            this.$set(this.formData, 'parentName', name);
          });
        }
      }
    },

// 专用方法：获取父级分类名称
    getParentName(parentId) {
      return new Promise((resolve) => {
        if (parentId === 0) return resolve("房屋类型管理");

        queryAllHouseTypes({ id: parentId }).then(ret => {
          resolve(ret.data?.[0]?.name || '未知分类');
        }).catch(() => {
          resolve('加载失败');
        });
      });
    },
    handleDelete(index, row) {
      if (row.children && row.children.length > 0) {
        this.$message.error('该分类下有子类，不能删除');
        return;
      }
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        handleDelete(row.id).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.queryAllHouseTypes();
        }).catch(error => {
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleConfirm() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.title === '新增房屋类型') {
            // 新增模式
            addHouseType(this.formData).then(ret => {
              this.$message({
                type: 'info',
                message: '新增成功!'
              });
              this.dialogVisible = false;
              this.queryAllHouseTypes()
            }).catch(err => {
              this.$message({
                message: '新增失败'
              })
            })
          } else {
            // 编辑模式
            this.formData.parentId = this.formData.parentId === 0 ? null : this.formData.parentId;
            editHouseType(this.formData).then(ret => {
              this.$message({
                type: 'info',
                message: '编辑成功!'
              });
              this.dialogVisible = false;
              this.queryAllHouseTypes()
            }).catch(err => {
              this.$message({
                message: '编辑失败'
              })
            })
          }
        } else {
          return false;
        }
      })
    },
  },
  created() {
    this.queryAllHouseTypes();
  }
}
</script>

<style scoped lang="scss">
.el-dialog {
  z-index:9999;
}

</style>
